﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IPC.Communication.Framework.Core;
using IPC.Communication.Framework.Core.Net;
using IPC.Communication.Framework.Reflection;

namespace IPC.Communication.Framework.Profinet.Freedom
{
    public class FreedomUdpNet : NetworkUdpDeviceBase
    {
        public FreedomUdpNet()
        {
            base.ByteTransform = new RegularByteTransform();
        }

        public FreedomUdpNet(string ipAddress, int port)
        {
            IpAddress = ipAddress;
            Port = port;
            base.ByteTransform = new RegularByteTransform();
        }

        [HslMqttApi("ReadByteArray", "特殊的地址格式，需要采用解析包起始地址的报文，例如 modbus 协议为 stx=9;00 00 00 00 00 06 01 03 00 64 00 01")]
        public override OperateResult<byte[]> Read(string address, ushort length)
        {
            OperateResult<byte[], int> operateResult = FreedomTcpNet.AnalysisAddress(address);
            if (!operateResult.IsSuccess)
            {
                return OperateResult.CreateFailedResult<byte[]>(operateResult);
            }
            OperateResult<byte[]> operateResult2 = ReadFromCoreServer(operateResult.Content1);
            if (!operateResult2.IsSuccess)
            {
                return operateResult2;
            }
            if (operateResult.Content2 >= operateResult2.Content.Length)
            {
                return new OperateResult<byte[]>(StringResources.Language.ReceiveDataLengthTooShort);
            }
            return OperateResult.CreateSuccessResult(operateResult2.Content.RemoveBegin(operateResult.Content2));
        }

        public override OperateResult Write(string address, byte[] value)
        {
            return Read(address, 0);
        }

        public override string ToString()
        {
            return String.Format("FreedomUdpNet<{0}>[{1}:{2}]", base.ByteTransform.GetType(), IpAddress, Port);
        }
    }
}